const vscode = require('vscode');
const path = require('path');
const { datefmt } = require('./src/date.js');
const { DragAndDropController } = require('./src/dragAndDropController.js');
const { JsonTreeDataProvider } = require('./src/jsonTreeDataProvider.js');
const {
	updateJsonFile_tag,
	updateJsonFile_content,
	importJsonData,
	exportJsonData,
} = require('./src/jsonFileUpdater.js');
const { getDownloadsPath } = require('./src/config.js');

// 激活插件
function activate(context) {
	// 注册 TreeDataProvider
	const treeDataProvider = new JsonTreeDataProvider(context);
	context.subscriptions.push(
		vscode.window.createTreeView(
			'snippetStorageId', // 必须与 package.json 中的 views.id 一致
			{
				treeDataProvider,
				showCollapseAll: true, // 全部折叠按钮
				canSelectMany: true, // 多选
				dragAndDropController: new DragAndDropController(treeDataProvider)
			}
		)
	);

	// 注册导出JSON命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.exportJson', async () => {
			const time = datefmt(new Date(), 'YYYYMMDD_HHmm');

			// 弹出保存路径选择
			const uri = await vscode.window.showSaveDialog({
				filters: { 'JSON Files': ['json'] },
				title: '选择保存位置',
				defaultUri: vscode.Uri.file(path.join(getDownloadsPath(), `snippets_${time}`))
			});

			if (!uri) return;

			exportJsonData(uri.fsPath, treeDataProvider);
		})
	);

	// 注册导入JSON命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.importJson', async () => {
			// 弹出文件选择对话框
			const uris = await vscode.window.showOpenDialog({
				canSelectMany: false, // 单选
				filters: { 'JSON Files': ['json'] }, // 文件类型过滤
				openLabel: '导入', // 按钮文字
				title: '选择要导入的 JSON 文件'
			});

			if (!uris || uris.length === 0) return;

			const filePath = uris[0].fsPath;
			importJsonData(context, filePath, () => {
				treeDataProvider.refresh()
			});
		})
	);

	// 注册过滤命令
	vscode.commands.executeCommand('setContext', 'filterState', 'idle')
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.filter', async () => {
			const keyword = await vscode.window.showInputBox({
				placeHolder: '输入关键字过滤，同时匹配名称和内容...',
			});
			if (keyword !== undefined) {
				treeDataProvider.filter(keyword);
				vscode.commands.executeCommand('setContext', 'filterState', 'filtering')
			}
		})
	)

	// 注册清除过滤命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.clearfilter', async () => {
			treeDataProvider.resetData()
			vscode.commands.executeCommand('setContext', 'filterState', 'idle')
		})
	)

	// 注册添加tag命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.addTag', async () => {
			// 弹出输入框修改tag名称
			const newValue = await vscode.window.showInputBox({
				prompt: '请输入分类名称',
				value: '',
			})
			if (newValue !== undefined) {
				updateJsonFile_tag(context, treeDataProvider, '', newValue);
			}
		})
	)

	// 注册编辑tag命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.editTag', async (selectedItem) => {
			// 弹出输入框修改tag名称
			const newValue = await vscode.window.showInputBox({
				prompt: '请输入分类名称',
				value: selectedItem.name || '' // 当前值作为默认值
			})
			if (newValue !== undefined) {
				updateJsonFile_tag(context, treeDataProvider, selectedItem, newValue);
			}
		})
	)

	// 注册删除tag命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.deleteTag', async (selectedItem) => {
			// 删除前确认提示
			const res = await vscode.window.showQuickPick(
				['删除分类(同时删除该分类下的片段)', '取消'], // 选项
			);
			if (res === '删除分类(同时删除该分类下的片段)') {
				updateJsonFile_tag(context, treeDataProvider, selectedItem);
			}
		})
	)

	// 注册点击item命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.pasteSnippet', (content) => {
			const editor = vscode.window.activeTextEditor;
			if (!editor) {
				vscode.window.showWarningMessage('请先打开一个文件！');
				return;
			}

			const cursorPosition = editor.selection.active; // 获取光标位置

			editor.edit((editBuilder) => {
				editBuilder.insert(cursorPosition, content); // content 是代码片段内容
			});
		})
	);

	// 注册添加item命令(右键保存代码片段)
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.saveSnippet', async () => {
			const treeData = treeDataProvider.getStorageData()
			if (treeData.length === 0) {
				vscode.window.showWarningMessage('请先添加分类！');
				return
			}

			// 获取代码片段
			const editor = vscode.window.activeTextEditor // 获取当前活动编辑器
			const selection = editor.selection // 获取当前选中的范围
			const selectedText = editor.document.getText(selection) // 获取选中范围的文本
			if (selectedText === '') {
				vscode.window.showWarningMessage('请先选中代码片段！');
				return
			}

			// 弹出输入框片段名称
			const itemName = await vscode.window.showInputBox({
				prompt: '请输入片段名称',
				value: '',
			})
			if (itemName === '') {
				vscode.window.showWarningMessage('片段名称必填！');
				return
			}

			// 单选片段分类
			const selectedTag = await vscode.window.showQuickPick(
				treeData.map(e => ({
					label: e.name,
					description: `包含 ${e.children?.length || 0} 个子项`,
					id: e.id,
				})), {
				placeHolder: '请选择分类',
				title: '分类选择',
				ignoreFocusOut: true // 点击外部不关闭
			});

			if (selectedTag) {
				updateJsonFile_content(context, treeDataProvider, '', {
					name: itemName,
					content: selectedText
				}, selectedTag.id);
			}
		})
	)

	// 注册编辑item命令
	let panel;
	let messageListener; // 存储当前的监听器
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.editItem', (selectedItem) => {
			if (!selectedItem) {
				vscode.window.showWarningMessage('未选中任何片段！');
				return;
			}
			if (!panel) {
				panel = vscode.window.createWebviewPanel(
					'editForm',
					'编辑片段',
					vscode.ViewColumn.One,
					{ enableScripts: true }
				);

				// Panel 关闭时清理引用
				panel.onDidDispose(() => {
					panel = undefined;
					messageListener?.dispose(); // 清理监听器
				});
			}

			panel.webview.html = `
			<!DOCTYPE html>
			<html>
			<head>
				<style>
					.form-group { margin:0 20px 5px 0; }
					label { display: block; margin-bottom: 5px; }
					input, textarea { width: 100%; padding: 8px; }
				</style>
			</head>
			<body>
				<div class="form-group">
					<label>名称</label>
					<input id="name" value="${selectedItem.name}">
				</div>
				<div class="form-group">
					<label>内容</label>
					<textarea id="content" rows="25">${selectedItem.content || ''}</textarea>
				</div>
				<button onclick="submit()">保存</button>
			
				<script>
					const vscode = acquireVsCodeApi();
					function submit() {
						const data = {
							name: document.getElementById('name').value,
							content: document.getElementById('content').value
						};
						vscode.postMessage(data);
					}
				</script>
			</body>
			</html>
			`;

			// 先清除之前的监听器
			if (messageListener) {
				messageListener.dispose();
			}
			messageListener = panel.webview.onDidReceiveMessage((data) => {
				updateJsonFile_content(context, treeDataProvider, selectedItem, data); // 自定义更新逻辑
				panel.dispose(); // 关闭面板
			});
		})
	);

	// 注册删除item命令
	context.subscriptions.push(
		vscode.commands.registerCommand('extension.deleteItem', async (selectedItem) => {
			// 删除前确认提示
			const res = await vscode.window.showQuickPick(
				['删除片段', '取消'], // 选项
			);
			if (res === '删除片段') {
				updateJsonFile_content(context, treeDataProvider, selectedItem);
			}
		})
	)
}

// 停用插件
function deactivate() { }

module.exports = {
	activate,
	deactivate
};